package com.fitso.model.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fitso.model.bean.nutrition.Food;
import com.fitso.model.dao.FoodDao;

/**
 * Hibernate implementation of {@link FoodDao}. This implementation converts the
 * food parts to base measurements when saving to the data store.
 * 
 * @author timothystorm
 * @see fitso.hbm.xml
 */
@Repository("HibernateFoodDao")
public class HibernateFoodDao extends HibernateBaseDao implements FoodDao {

	public void delete(Food food) {
		t().delete(food);
	}

	public List<Food> read() {
		return toList(t().loadAll(Food.class), Food.class);
	}

	public Food readById(Long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Food.class);
		criteria.add(Property.forName("id").eq(id));

		return firstItem(t().findByCriteria(criteria), Food.class);
	}

	public List<Food> readById(List<Long> ids) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Food.class);
		criteria.add(Restrictions.in("id", ids.toArray()));

		return toList(t().findByCriteria(criteria), Food.class);
	}

	public void createOrUpdate(Food food) {
		t().saveOrUpdate(food);
	}

	public void createOrUpdate(List<Food> foods) {
		t().saveOrUpdateAll(foods);
	}

	public void delete(List<Food> foods) {
		t().deleteAll(foods);
	}
}
